import React, { ReactElement, useState, useEffect } from 'react';
import {
  Image,
  ImageProps,
  NativeSyntheticEvent,
  ImageErrorEventData,
  ImageStyle
} from 'react-native';
import WebView from 'react-native-webview';

import Log from '../../common/log';

const renderHtml = (source: string): string => {
  return `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="format-detection" content="telephone=no"><meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"><meta name="viewport" content="with=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1"><title>agan-chart</title><style type="text/css">html, body{margin: 0;padding: 0;}body{width: 100%;height: 100%;height: 100vh;background: #fff;}.main{width: 100%;min-height: 100%;}</style><body><img class="main" src="${source}" /></body></html>`;
};

interface Props extends ImageProps {
  source: any;
  style?: ImageStyle | ImageStyle[];
  showWidth: number;
  useWebView?: boolean;
  onCustomLayout?: (height: number) => void;
}

const AdaptImage = (props: Props): ReactElement => {
  const {
    source,
    style,
    showWidth = 0,
    onError,
    useWebView,
    onCustomLayout
  } = props;

  const [showHeight, setShowHeight] = useState<number>(0);

  useEffect((): void => {
    if (source.uri) {
      // uri图片
      Image.getSize(
        source.uri,
        (width, height): void => {
          if (!showHeight) {
            setShowHeight((showWidth * height) / width);
            if (onCustomLayout) {
              onCustomLayout((showWidth * height) / width);
            }
          }
        },
        (e): void => {
          Log.e('Image load failed', JSON.stringify(e));
        }
      );
    } else {
      // 本地图片
      const result = Image.resolveAssetSource(source);
      const { height, width } = result;
      if (!showHeight && height && width) {
        setShowHeight((showWidth * height) / width);
      }
    }
  }, []);

  if (useWebView) {
    return (
      <WebView
        showsVerticalScrollIndicator={false}
        showsHorizontalScrollIndicator={false}
        cacheEnabled
        scrollEnabled={false}
        style={{ width: showWidth || 0, height: showHeight || 0 }}
        originWhitelist={['*']}
        source={{ html: renderHtml(source.uri) }}
      />
    );
  }

  return (
    <Image
      {...props}
      style={[style, { width: showWidth || 0, height: showHeight || 0 }]}
      onError={(err: NativeSyntheticEvent<ImageErrorEventData>): void => {
        if (onError) {
          onError(err);
        }
        Log.e('Image load', err.nativeEvent.error);
      }}
    />
  );
};

export default AdaptImage;
